Factory Pattern

1 min read
Rapid overview

Factory Pattern — Centralized object creation

Provide a single place to create related objects without exposing construction details.


Example (TypeScript)

type ApiClient = { get: (path: string) => Promise<unknown> };

type ClientConfig = { baseUrl: string; token?: string };

const createApiClient = ({ baseUrl, token }: ClientConfig): ApiClient => ({
  get: (path) =>
    fetch(`${baseUrl}${path}`, {
      headers: token ? { Authorization: `Bearer ${token}` } : undefined
    }).then((res) => res.json())
});

Why it matters

  • Centralizes creation logic for shared dependencies.
  • Makes testing easier by swapping factories.
  • Helps enforce consistent configuration.

Questions & Answers

Q: When do you use a factory?

A: When object creation requires configuration, caching, or runtime selection.

Q: Factory vs Builder?

A: Factory returns a ready instance; Builder assembles complex objects step-by-step.